package com.zky.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Lists;
import com.zky.common.constant.ProductConstant;
import com.zky.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.zky.gulimall.product.dao.AttrGroupDao;
import com.zky.gulimall.product.dao.CategoryDao;
import com.zky.gulimall.product.entity.*;
import com.zky.gulimall.product.service.CategoryService;
import com.zky.gulimall.product.vo.AttrGroupRelationVo;
import com.zky.gulimall.product.vo.AttrRespVo;
import com.zky.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zky.common.utils.PageUtils;
import com.zky.common.utils.Query;

import com.zky.gulimall.product.dao.AttrDao;
import com.zky.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);

        if(attr.getAttrType()== ProductConstant.AttrEnum.ATTR_BASE_TYPE.getCode() && attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttr(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(attrType)?1:0);
        Object key = params.get("key");
        if (catelogId != null && catelogId != 0) {
            queryWrapper.eq("catelog_Id", catelogId);
        }
        if (Objects.nonNull(key)) {
            String key1 = (String) params.get("key");
           if(!StringUtils.isEmpty(key1)){
               queryWrapper.and(wrapper -> {
                   wrapper.eq("attr_id", key1).or().like("attr_name", key1);
               });
           }
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVoList;
        if (!CollectionUtils.isEmpty(records)) {
            respVoList = records.stream().map(item -> {
                AttrRespVo attrRespVo = new AttrRespVo();
                BeanUtils.copyProperties(item, attrRespVo);

                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId()));
                if (relationEntity != null && relationEntity.getAttrGroupId()!=null) {
                    AttrGroupEntity groupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(groupEntity.getAttrGroupName());
                }

                CategoryEntity categoryEntity = categoryDao.selectById(item.getCatelogId());
                if (categoryEntity != null) {
                    attrRespVo.setCatelogName(categoryEntity.getName());
                }
                return attrRespVo;
            }).collect(Collectors.toList());
        } else {
            respVoList = Lists.newArrayList();
        }

        pageUtils.setList(respVoList);

        return pageUtils;
    }

    @Cacheable(value = "attr",key = "'attrInfo:'+#root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity entity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(entity, attrRespVo);

        if(entity.getAttrType()== ProductConstant.AttrEnum.ATTR_BASE_TYPE.getCode()){
            //设置分组信息
            AttrAttrgroupRelationEntity selectOne = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (selectOne != null) {
                attrRespVo.setAttrGroupId(selectOne.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(selectOne.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //设置分类信息
        Long[] categoryPath = categoryService.findCategoryPath(entity.getCatelogId());
        attrRespVo.setCatelogPath(categoryPath);
        CategoryEntity categoryEntity = categoryDao.selectById(entity.getCatelogId());
       if(categoryEntity!=null){
           attrRespVo.setCatelogName(categoryEntity.getName());
       }
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        if(attrEntity.getAttrType()== ProductConstant.AttrEnum.ATTR_BASE_TYPE.getCode()){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            Integer integer = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if(integer!=null&&integer>0){
                //修改分组关联
                attrAttrgroupRelationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            }else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }

    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrGroupId = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        if(CollectionUtils.isEmpty(attrGroupId)){
            return null;
        }
        List<Long> longList = attrGroupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        if(CollectionUtils.isEmpty(longList)){
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(longList);
        return (List<AttrEntity>)attrEntities;
    }

    @Override
    public void deleteRelation(List<AttrGroupRelationVo> relationVos) {
        List<AttrAttrgroupRelationEntity> entityList = relationVos.stream().map(item -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        for (AttrAttrgroupRelationEntity entity : entityList) {
            System.out.println("entity:"+entity);
        }
        attrAttrgroupRelationDao.deleteBatchs(entityList);
    }

    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        if(attrGroupEntity==null){
            return null;
        }

        //2 当前分组只能关联别的分组没有引用的属性
        List<AttrGroupEntity> catelog_id = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", attrGroupEntity.getCatelogId()));
        //先找当前分类下其他分组
        List<Long> longList=Lists.newArrayList();
        if(!CollectionUtils.isEmpty(catelog_id)){
            List<Long> longs = catelog_id.stream().map(item -> {
                return item.getAttrGroupId();
            }).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(longs)){
                //这些分组关联的属性
                List<AttrAttrgroupRelationEntity> entityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", longs));
                if(!CollectionUtils.isEmpty(entityList)){
                    longList = entityList.stream().map(e -> {
                        return e.getAttrId();
                    }).collect(Collectors.toList());
                }
            }
        }
        //从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", attrGroupEntity.getCatelogId()).eq("attr_type",ProductConstant.AttrEnum.ATTR_BASE_TYPE.getCode());
        if(!CollectionUtils.isEmpty(longList)){
            queryWrapper.notIn("attr_id", longList);
        }
        Object key = params.get("key");
        if(Objects.nonNull(key)){
            queryWrapper.and(w->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIdList) {
        return baseMapper.selectSearchAttrIds(attrIdList);
    }

}